import React, { memo, Component } from 'react'
import { baseUrl } from '../../assets/baseUrl'
import { Tabs, Button, Select, Tooltip, message } from 'antd'
import { getClassmates, getTempLi, getCrop, getAllStudyDetail, getStudyDetail, sendEmail, sendQQEmail } from '@/api/user'
import { StudentInfo } from '../../utils/model'
import './index.css'
import './index.less'
import * as echarts from 'echarts';
const BaseUrl = baseUrl()
const { TabPane } = Tabs;
const { Option } = Select;

class homeWork extends Component {
    static contextType = StudentInfo
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            nickName: null, //昵称
            homeworkList: [],  //作业列表
            handleHistory: [], //提交历史
            botName: null,  //团支部名称
            totalCount: null,   //班级总人数
            classmateList: [], //班级成员列表（昵称与studentId）
            temp: [], //青年大学习期数
            selectTemp: null, //选中的期数
            schoolName: null, //学校名
            academy: null, //学院名称
            selectTableName: null, //选中的期数对应数据库表名
            studyDetail: [], //本期青年大学习学习情况
            level: null, //权限等级
            schoolLevel: null, //校园等级
            cropSource: [], //院校大学习情况
        }
    }
    ChangeHistory = (url) => {
        this.props.history.push(url);
    }
    componentDidMount() {
        this.setState({
            nickName: this.context?.studentInfo?.nickName,
            level: this.context?.studentInfo?.level,
            schoolLevel: this.context?.studentInfo?.schoollevel,
        },()=>{
            if (this.context?.studentInfo?.classId) {
                this.getClassmate()
                this.getTemp()
                this.getCorpInfo()
            }
            else {
                message.error('请先加入班级哦～')
            }
        })
    }

    //全院图表绘制
    echartAll = () => {
        let myChart = echarts.init(document.getElementById('otherMain'), 'dark');
        let { selectTemp, cropSource, academy } = this.state
        console.log(cropSource);
        const option = {
            title: {
                text: academy + '       ' + selectTemp + '青年大学习',
                subtext: '学习情况实时监控',
            },
            xAxis: {
                type: 'category',
                data: cropSource.map((item, index) => { return index+1 }),
                splitNumber: cropSource.length
            },
            yAxis: {
                type: 'value'
            },
            series: [
                {
                    data: cropSource.map(item => { return (item.completeNum / item.classPersonNum * 100).toFixed(0) }),
                    type: 'bar',
                    showBackground: true,
                    backgroundStyle: {
                        color: 'rgba(180, 180, 180, 0.2)'
                    }
                }
            ],
            tooltip: {
                show: true,
                formatter: function (params) {
                    let classMess = cropSource[Number(params.name-1)]
                    return (
                        `${classMess.className}<br>总人数：${classMess.classPersonNum}人<br>已完成：${classMess.completeNum}人<br>完成率：${(classMess.completeNum / classMess.classPersonNum * 100).toFixed(0)}%<br>未完成名单：${classMess?.inComplete.length ===0?'无':classMess?.inComplete
                            .map((i, index) => {
                                return i.realName + ((index % 3 == 0) ? '<br>' : '  ')
                            }).join('')}`
                    );
                }
            },
        };

        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option);
    }

    //本班图表绘制
    echart = () => {
        let myChart = echarts.init(document.getElementById('main'));
        let { selectTemp, botName, studyDetail, noStudy } = this.state
        // 指定图表的配置项和数据
        let option = {
            title: {
                text: `${selectTemp}`,
                subtext: `${botName}`,
                left: 'center'
            },
            tooltip: {
                trigger: 'item'
            },
            legend: {
                orient: 'vertical',
                // left: 'left'
                right: 'right'
            },
            series: [
                {
                    name: '人数',
                    type: 'pie',
                    radius: '50%',
                    data: [
                        { value: studyDetail?.length, name: '已学习' },
                        { value: noStudy?.length, name: '未学习' },
                    ],
                    color: ['#63cdff', '#ff6b6b'],
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }
            ]
        };

        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option);
    }
    //获取班级同学名单
    getClassmate = () => {
        getClassmates().then((res) => {
            this.setState({
                classmateList: res.data?.data,
                totalCount: res.data?.data.length
            })
        })
    }

    //获取青年大学习期数
    getTemp = () => {
        getTempLi().then((res) => {
            this.setState({
                temp: res?.data.list,
                selectTemp: res?.data.list[0].name,
                selectTableName: res?.data.list[0].table_name,
            })
        })
    }

    //获取团支部信息
    getCorpInfo = () => {
        getCrop().then((res) => {
            this.setState(
                state => ({
                    botName: res.data?.data.corpCellName,
                    schoolName: res.data?.data.schoolName,
                    academy: res.data?.data.academy
                }),
                () => this.getStuDetail()
            )
        })
    }

    //获取本期学习详情
    getStuDetail = () => {
        let { selectTableName, schoolName, academy, botName, selectTemp, schoolLevel } = this.state
        if (!(botName && schoolName && academy && selectTableName)) {
            setTimeout(() => {
                this.getStuDetail()
            }, 100);
            return
        }
        let data = {
            table_name: selectTableName,
            level1: '直属高校',
            level2: schoolName,
            level3: academy,
            level4: botName,
            tempName: selectTemp
        }
        getStudyDetail(data).then((res => {
            let studyDetail = res?.data.list.list
            let { classmateList } = this.state
            let noStudy = []
            let hasstudy = false
            classmateList.map((item) => {
                studyDetail.map((i) => {
                    if (i.username === item.realName)
                        hasstudy = true
                })
                if (hasstudy) {
                    hasstudy = false
                    return
                }
                noStudy.push({ name: item.realName || '未实名用户', studentId: item.studentId, QQnumber: item.QQnumber })
            })
            this.setState({
                studyDetail,
                noStudy
            }, () => {
                this.echart()
            })
        }))
        if (schoolLevel.split(',').includes('68'))
            getAllStudyDetail(data).then((res => {//获取全院的详情
                message.success('获取成功')
                this.setState({
                    cropSource: res.data.data.sort((a, b) => { return b.classPersonNum - a.classPersonNum })
                }, () => {
                    this.echartAll()
                })

            }))
    }

    //选择期数
    selectTemp = (e) => {
        let { temp } = this.state
        let tableName = ''
        temp.map((item) => {
            if (item.name === e)
                tableName = item.table_name
        })
        this.setState({
            selectTemp: e,
            selectTableName: tableName
        }, () => this.getStuDetail())
    }
    sendWarn = () => {
        // sendEmail
        let { noStudy, selectTemp, nickName } = this.state
        let data = {
            content: `请尽快完成${selectTemp}青年大学习！`,
            title: `${selectTemp}青年大学习提醒`,
        }
        noStudy.map((item) => {
            data.studentId = item.studentId
            data.name = item.name
            data.content = `尊敬的${item.name}同学，${nickName}提醒您：${selectTemp}即将截止，请尽快完成${selectTemp}青年大学习，祝您学习进步，生活愉快，比心~`
            sendEmail(data)
            if (item.QQnumber) {
                data.QQnumber = item.QQnumber
                sendQQEmail(data).then(res => {
                    console.log(res.data);
                })
            }
        })
        message.success('已全部发送邮件提醒')
    }
    render() {
        const { botName, totalCount, classmateList, temp, selectTemp, studyDetail, noStudy, level, schoolLevel } = this.state
        return (
            <>
                <div style={{ padding: '5vh 5vw' }} className='studyPage'>
                    <div className="class-message-box">
                        <div className="bot-name-box">
                            <div className="label">团支部名称：</div>
                            <div className="bot-name">{botName}</div>
                            <Tooltip title="查询青年大学习名单需保持团支部名称与小程序中本班团支部名称一致，若不一致可联系班长在个人中心设置本班团支部名称哦~">
                                <i className="iconfont icon-bangzhu bangzhu"></i>
                            </Tooltip>
                        </div>
                        <div className="choose-temp">
                            <div className="label">选择期数：</div>
                            <Select value={selectTemp} className="select-choose" onChange={e => this.selectTemp(e)} >
                                {
                                    temp && temp.map((item) => {
                                        return <Option value={item.name}>{item.name}</Option>
                                    })
                                }
                            </Select>
                        </div>
                    </div>
                    <div className="button-boxs">
                        {level == 10 && <div className="button-warn" onClick={this.sendWarn.bind(this)}>一键提醒</div>}
                    </div>
                    <div className="work-outer-box">
                        <div className="work-left-box">
                            <div className="mess-title">
                                应学习人数：<div className="number">{totalCount}</div>
                            </div>
                            <div className="name-all-box">
                                {
                                    classmateList && classmateList?.map((item, index) => {
                                        return (
                                            <span className="tag">{item.realName || '未实名用户'}</span>
                                        )
                                    })
                                }
                            </div>
                        </div>
                        <div className="work-center-box">
                            <div className="box-1">
                                <div className="mess-title">
                                    已学习人数：<div className="number">{studyDetail.length}</div>
                                </div>
                                <div className="mess-box">
                                    {
                                        studyDetail && studyDetail.map((item, index) => {
                                            return (
                                                <Tooltip title={`学习日期${item.addtime}`}>
                                                    <span className="tag">{item.username}</span>
                                                </Tooltip>
                                            )
                                        })
                                    }
                                </div>
                            </div>
                            <div className="box-2">
                                <div className="mess-title">
                                    未学习人数：<div className="number">{noStudy?.length}</div>
                                </div>
                                <div className="mess-box">
                                    {
                                        noStudy && noStudy.map((item, index) => {
                                            return <span className="tag">{item.name}</span>
                                        })
                                    }
                                </div>
                            </div>
                        </div>
                        <div className="echart-right-box">
                            <div id="main" style={{ width: 350, height: 350 }}></div>
                        </div>
                    </div>
                </div>
                {schoolLevel.split(',').includes('68') && <div style={{ padding: '5vh 5vw', marginTop: '5vh' }} className='studyPage'>

                    <div className="work-outer-box" style={{ backgroundColor: 'rgb(16,12,42)' }}>

                        {/* <div style={{ flex:5 }}></div> */}
                        <div id="otherMain" style={{ flex: 10, height: 700 }}></div>

                    </div>
                    <div>
                        <Button onClick={() => {
                            document.getElementById('otherMain').removeAttribute('_echarts_instance_');
                            this.getStuDetail()
                        }} type='primary' style={{ marginLeft: '47%', marginTop: 26 }}>获取最新实时数据</Button>
                    </div>
                </div>}
            </>
        )
    }
}
export default memo(homeWork)